<?php
/**
 * (jobs)
 */
namespace App\Jobs\OverSeasIn;

use App\Models\OverSeasBa\RemovaleInventoryFNSku;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
class RemovaleOrderDetailStatus implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $removaleOrderDetails;

    /**
     * RemovaleOrderDetailStatus constructor.
     * @param $removaleOrderDetails
     */
    public function __construct($removaleOrderDetails)
    {
        $this->removaleOrderDetails = $removaleOrderDetails;
    }

    /**
     * Execute the job.
     * @return void
     */
    public function handle()
    {
        $this->exeFillData($this->removaleOrderDetails);
    }

    private function exeFillData($removaleOrderDetails){
        foreach ($removaleOrderDetails as $removaleOrderDetail){
            $inventory = RemovaleInventoryFNSku::query()
                ->firstOrNew(
                    [
                        'account_id' => $removaleOrderDetail->account_id,
                        'warehouse_id' => $removaleOrderDetail->warehouse_id,
                        'fnsku' => $removaleOrderDetail->fnsku,
                    ],[
                        'psku_id' => $removaleOrderDetail->psku_id,
                    ]
                );
            if($removaleOrderDetail->status == 2){
                //订单已完结
                //在途 = 发运数量 - (已入库数量 + 本次入库数量)
                $transit = $removaleOrderDetail->shipped_quantity - ($removaleOrderDetail->ship_quantity + $removaleOrderDetail->this_quantity);
                if ($transit < 0) $transit = 0;
                $inventory->transit -= min($inventory->transit,$transit);
            }else{
                //订单未完结
                //在途 = 本次入库数量
                $transit = $removaleOrderDetail->this_quantity;
                $inventory->transit -= min($inventory->transit,$transit);
            }

            //海外仓在库
            $inventory->instant += $removaleOrderDetail->this_quantity;
            $inventory->save();
        }
    }
}
